#include "trunk_privutils.h"

int mrr_trunk_read(void *buf, size_t wanted, mrr_phypos *locp) {

	norm_phy_location(locp);

	FILE *filep;
	if (open_trunkfile(locp->trunkno, &filep) != 0) {

		return 1;
	}

	fpos_t begin = locp->offset + TRUNK_HEADER_LENGTH;
	if (fsetpos(filep, &begin) != 0) {

		mrr_sys_errno();
		fclose(filep);
		return 1;
	}

	int offset = locp->offset;
	trunk_sn_t sn = locp->trunkno;

	for (;;) {

		int coping;
		if (wanted < TRUNK_SIZE - offset) {
			coping = wanted;
		} else {
			coping = TRUNK_SIZE - offset;
		}

		int done = fread(buf, 1, coping, filep);
		if (done != coping) {

			mrr_warn("trunk(%d) incomplete, read: pos=%d, wanted=%d, done=%d bytes",
					sn, offset, coping, done);
			return 1;
		} else {
			mrr_trace("read. trunk %d, pos %d, done %d bytes",
					sn, offset, done);
		}

		wanted -= done;
		if (wanted == 0) {
			// complete the reading
			fclose(filep);
			return 0;

		} else {
			// continue with the next trunk
			buf += coping;
			sn++;
			fclose(filep);
			open_trunkfile(sn, &filep);
			offset=0;
		}
	};
}
